package com.kl.modular.sysman.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.kl.modular.common.controller.BaseController;
import com.kl.modular.common.response.ResponseBase;
import com.kl.modular.sysman.system.service.api.ISystemAreaCacheService;
import com.kl.modular.system.dao.model.SystemArea;
import com.kl.modular.system.service.api.ISystemAreaService;
import com.kl.modular.system.service.api.ISystemParamService;
import com.kl.modular.system.service.bo.SystemAreaBo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 * @author xr_zjb
 * @date 2017-09-06 16:26
 * @(C) xinrui Copyright 
 */
@Controller
public class SystemAreaController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(SystemAreaController.class);
	
	@Autowired
	private ISystemAreaService systemAreaService;

	@Autowired
	private ISystemAreaCacheService systemAreaCacheService;
	@Autowired
	private ISystemParamService systemParamService;

	/**  view */
	private static String pathSystemAreaRoot="/sysman/system/area/";
	
	/**
	 * 添加页面
	 * @return
	 */
	@RequestMapping(value="/sysman/systemArea/toSystemAreaAdd" , method = RequestMethod.GET)
	@RequiresPermissions("sysman:SYSTEM_AREA_MAN:add")
	public String toAddSystemArea(Long areaId, HttpServletRequest request){
		logger.info("行政区域添加页面");
		if (areaId != null){
			SystemArea systemArea = systemAreaService.selectById(areaId);
			request.setAttribute("parentid", systemArea.getId());
			request.setAttribute("level", systemArea.getLevel() + 1);
			if (systemArea.getLevel()==0){
				request.setAttribute("position", "tr_0");
			}else {
				request.setAttribute("position", systemArea.getPosition()+" tr_"+systemArea.getId());
			}

		}
		return pathSystemAreaRoot + "addSystemArea.ftl";
	}
	
	/**
	 * 添加
	 */
	@RequestMapping(value="/sysman/systemArea/addSystemArea" , method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions("sysman:SYSTEM_AREA_MAN:add")
	public String addSystemArea(@Valid SystemArea systemArea, BindingResult result, HttpServletResponse response) throws Exception{
		logger.info("添加>>data:" + JSON.toJSONString(systemArea));

		if (result.hasErrors()) {
			return ResponseBase.errorStr(result.getAllErrors().get(0).getDefaultMessage());
		}

		SystemAreaBo systemAreaBo = new SystemAreaBo();
		systemAreaBo.setId(systemArea.getId());
		SystemArea systemAreaData = systemAreaService.selectOneByBo(systemAreaBo);
		if(systemAreaData != null){
			return ResponseBase.errorStr("行政区域ID"+systemAreaData.getId()+"已被行政区域 ”" + systemAreaData.getAreaname() + "”使用");
		}

		systemAreaService.insert(systemArea);
		//更新缓存
		new Thread(new Runnable() {

			@Override
			public void run() {
				systemAreaCacheService.refreshAreaCache();
			}
		}).start();

		String jsonstr = ResponseBase.success();
		logger.info("添加>>返回>>data:" + jsonstr);
		return jsonstr;
	}

	
	/**
	 * 更新页面
	 * @return
	 */
	@RequestMapping(value = "/sysman/systemArea/toChangeView" , method = RequestMethod.GET)
	@RequiresPermissions("sysman:SYSTEM_AREA_MAN:update")
	public String toChangeSystemArea(Long id, HttpServletRequest request) throws Exception{
		logger.info("修改页面>>data:" + id);
		SystemArea systemArea = systemAreaService.selectById(id);
		request.setAttribute("systemArea", systemArea);
		return pathSystemAreaRoot + "systemAreaUpChange.ftl";
	}

	
	/**	
	 * 修改
	 */
	@RequestMapping(value = "/sysman/systemArea/upChange" , method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions("sysman:SYSTEM_AREA_MAN:update")
	public String upChangeSystemArea(@Valid SystemArea systemArea, BindingResult result, HttpServletResponse response) throws Exception{
		logger.info("更新信息>>data:" + JSON.toJSONString(systemArea));

		if (result.hasErrors()) {
			return ResponseBase.errorStr(result.getAllErrors().get(0).getDefaultMessage());
		}
		if(systemArea.getId() == null){
			return ResponseBase.errorStr(ResponseBase.RESPOSNE_NOT_VALID_ERROR);
		}

		systemAreaService.updateById(systemArea);
		//更新缓存
		new Thread(new Runnable() {

			@Override
			public void run() {
				systemAreaCacheService.refreshAreaCache();
			}
		}).start();

		String jsonstr = ResponseBase.success();
		logger.info("编辑信息>>返回>>data:" + jsonstr);
		return jsonstr;
	}

	/**
	 * 批量删除
	 */
	@RequestMapping(value = "/sysman/systemArea/delSystemArea" , method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions("sysman:SYSTEM_AREA_MAN:delete")
	public String delSystemArea(Long id,HttpServletResponse response) throws Exception{
		logger.info("删除>>data:" + JSON.toJSONString(id));

		// 数据验证
		if (id == null) {
			return ResponseBase.errorStr(ResponseBase.RESPOSNE_NOT_VALID_ERROR);
		}

		List<SystemArea> systemAreaList = systemAreaService.getSubAreaList(id);

		if (systemAreaList.size()>0){
			return ResponseBase.errorStr("无法删除！该行政区域下存在下级行政区域，请先删除下级行政区域");
		}

		systemAreaService.deleteById(id);
		//更新缓存
		new Thread(new Runnable() {

			@Override
			public void run() {
				systemAreaCacheService.refreshAreaCache();
			}
		}).start();

		String jsonstr = ResponseBase.success();
		logger.info("删除资源>>返回view>>data:" + jsonstr);
		return jsonstr;
	}


	/**
	 * 根据父级ID查找子集
	 * @param parentId
	 * @return
	 */
	@RequestMapping(value = "/sysman/systemArea/findChildAreaAllList", method = RequestMethod.POST)
	@ResponseBody
	public String findChildAreaAllList(Long parentId){
		List<SystemArea> childList = systemAreaCacheService.findChildAllList(parentId);
		return JSON.toJSONString(childList);
	}

	/**
	 * 获取当前area信息
	 * @return
	 */
	@RequestMapping(value = "/sysman/systemArea/presentAreaInfo",method = RequestMethod.POST)
	@ResponseBody
	public String getAreaLevel(){
		Long nowAreaId = getAreaId();
		SystemArea area = systemAreaCacheService.findAreaById(nowAreaId);
		Long parentAreaId = area.getParentid();
		long level = area.getLevel().longValue() ;
		Long provinceId = 0L;
		Long cityId = 0L;
		Long countyId = 0L;
		if(level == 0){
			//全国
		} else if(level == 1){
			//省一级 eg.浙江省
			provinceId = nowAreaId;
		} else if(level == 2){
			//市一级 eg.杭州市
			provinceId = parentAreaId;
			cityId = nowAreaId;
		} else if(level == 3){
			//区、县一级 eg.上城区
			SystemArea city = systemAreaCacheService.findAreaById(parentAreaId);
			provinceId = city.getParentid();
			cityId = parentAreaId;
			countyId = nowAreaId;
		} else if(level ==4){
			//派出所 没什么好选的，不给选
		}
		Map<String,Long> map = new HashMap<String, Long>();
		map.put("provinceId",provinceId);
		map.put("cityId",cityId);
		map.put("countyId",countyId);
		map.put("level",level);
		return JSON.toJSONString(map);
	}

}
